package gops

import (
	"github.com/shirou/gopsutil/process"
)

type Process struct {
	*process.Process
}

func NewProcess(pid int) (p Process, err error) {
	mp, err := process.NewProcess(int32(pid))
	if err != nil {
		return
	}
	return Process{
		Process: mp,
	}, nil
}


type ProcInfo struct {
	Pid  int     `json:"pid"`
	Pids []int   `json:"pids"`
	Rss  int     `json:"rss"`
	PCpu float64 `json:"pcpu"`
}

func (pi *ProcInfo) Add(add ProcInfo) {
	pi.Rss += add.Rss
	pi.PCpu += add.PCpu
}

// CPU Percent * 100
func (p *Process) ProcInfo() (pi ProcInfo, err error) {

	pi.PCpu,_ =  p.CPUPercent()
	info,_ := p.MemoryInfo()
	pi.Rss = int(info.RSS)
	pi.Pid = int(p.Pid)
	childs := p.child()

	pi.Pids = make([]int,0)
	for _,child:=range childs {
		pi.Pids = append(pi.Pids,int(child.Pid))
	}

	return
}


// Get all child process
func (p *Process) child() (cps []Process) {
	ps,_ := p.Children()
	for _,p:= range ps {
		cps = append(cps, Process{p})
	}
	return cps
}

//Sum everything
func (p *Process) ChildrenProcInfo() (pi ProcInfo) {
	cps:= p.child()
	for _, cp := range cps {
		info, er := cp.ProcInfo()
		if er != nil {
			continue
		}
		pi.Add(info)
		pi.Pids = append(pi.Pids, int(cp.Pid))
	}
	pi.Pid = int(p.Pid)
	return
}
